package com.questetra.bpms.gae.forms.server;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.questetra.bpms.gae.forms.client.MessageData;
import com.questetra.bpms.gae.forms.client.MessageService;

/**
 * The server side implementation of the RPC service.
 * 
 * @author Tsuyoshi Kusaka
 */
@SuppressWarnings("serial")
public class MessageServiceImpl extends RemoteServiceServlet implements MessageService {

    @Override
    public void sendMessageData(MessageData data) throws IllegalArgumentException {

        //TODO validation
//        if (!FieldVerifier.isValidName(input)) {
//        // If the input is not valid, throw an IllegalArgumentException back to
//        // the client.
//            throw new IllegalArgumentException(
//                "Name must be at least 4 characters long");
//        }

//        System.out.println("data size:" + data.getDataMap().size());

        try {
            //TODO modify
            URL url = new URL("https://s.questetra.net/00000000/System/Event/MessageStart/start?processModelInfoId=1&nodeNumber=0&key=xxxxxxxxxx");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");

            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
            String parameter = "";
            for (Map.Entry<String, String> e : data.getDataMap().entrySet()) {
                parameter += e.getKey() + "=" + URLEncoder.encode(e.getValue(), "UTF-8") + "&";
            }
            parameter = parameter.substring(0, parameter.length() - 1);
            System.out.println("message data:" + parameter);
            writer.write(parameter);
            writer.close();
    
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                // OK
                System.out.println("HTTP_OK");
            } else {
                // Server returned HTTP error code.
                System.out.println("HTTP_NG:" + connection.getResponseCode());
            }
        } catch (MalformedURLException e) {
            System.out.println("MalformedURLException:" + e.getMessage());
        } catch (IOException e) {
            System.out.println("IOException:" + e.getMessage());
        }

    }
}
